package com.example.aiinterview.config;

import com.example.aiinterview.model.User;
import com.example.aiinterview.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

/**
 * 系统启动数据初始化器
 * 在应用启动后自动创建默认的管理员和测试用户。
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class DataInitializer implements CommandLineRunner {

    private final UserService userService;

    private static final String DEFAULT_ADMIN_USERNAME = "admin";
    private static final String DEFAULT_TEST_USERNAME = "testuser";

    @Override
    public void run(String... args) {
        log.info("开始初始化系统数据...");

        createDefaultAdmin();
        createTestUser();

        log.info("系统数据初始化完成。");
    }

    private void createDefaultAdmin() {
        try {
            User existingAdmin = userService.findByUsername(DEFAULT_ADMIN_USERNAME);
            if (existingAdmin == null) {
                User adminUser = userService.registerNewUser(
                        DEFAULT_ADMIN_USERNAME,
                        "admin123",
                        "admin@example.com",
                        "系统管理员",
                        User.Role.ADMIN
                );
                log.info("默认管理员用户创建成功。用户名: {}, 用户ID: {}", DEFAULT_ADMIN_USERNAME, adminUser.getId());
            } else {
                // 确保现有用户的角色正确
                if (existingAdmin.getRole() != User.Role.ADMIN) {
                    existingAdmin.setRole(User.Role.ADMIN);
                    userService.saveUser(existingAdmin);
                    log.info("已更新用户 '{}' 的角色为 ADMIN", DEFAULT_ADMIN_USERNAME);
                } else {
                    log.info("管理员用户 '{}' 已存在且角色正确。", DEFAULT_ADMIN_USERNAME);
                }
            }
        } catch (Exception e) {
            log.error("创建或更新默认管理员用户失败", e);
        }
    }

    private void createTestUser() {
        try {
            if (!userService.existsByUsername(DEFAULT_TEST_USERNAME)) {
                User testUser = userService.registerNewUser(
                        DEFAULT_TEST_USERNAME,
                        "test123",
                        "test@example.com",
                        "测试用户",
                        User.Role.USER
                );
                log.info("测试用户创建成功。用户名: {}, 用户ID: {}", DEFAULT_TEST_USERNAME, testUser.getId());
            } else {
                log.info("测试用户 '{}' 已存在，跳过创建。", DEFAULT_TEST_USERNAME);
            }
        } catch (Exception e) {
            log.error("创建测试用户失败", e);
        }
    }
}